import {createStore} from 'vuex'
import $ from "jquery"

export default class store {
    store = null
    options = {
        state: {
            userInfo: null,
            refreshTime: null,
            _systemConfig: {
                theme: "default",
                logoSrc: "",
                menuTheme: "default",
                style: {
                    bgColor: "#fff",        // 全局背景色
                    menu: {}
                },
            },
            targetPageActive: true,    // 当前页面是否激活
            currentPagePath: null,
            pagesList: [],
            pagesHistoryList: [],
            defaultRoutePath: null,
            menuData: [],
            routerData: [],
            apiData: []
        },
        mutations: {

            /**
             * 设置用户信息
             * @param state
             * @param userInfo
             */
            setUserInfo(state, userInfo) {
                if (userInfo) {
                    sessionStorage.setItem("userInfo", JSON.stringify(userInfo))
                } else {
                    sessionStorage.removeItem('userInfo')
                    sessionStorage.removeItem('token')
                }
                state.userInfo = userInfo;
            },

            /**
             * 更新用户信息
             * @param state
             * @param userInfo
             */
            updateUserInfo(state, userInfo) {
                state.userInfo = { ...state.userInfo, ...userInfo };
                sessionStorage.setItem("userInfo", JSON.stringify(state.userInfo))
            },

            /**
             * 设置定时刷新session任务
             * @param state
             * @param refreshTime
             */
            setRefreshTime(state, refreshTime) {
                state.refreshTime = refreshTime
            },

            /**
             * 清除定时刷新session任务
             * @param state
             */
            clearRefreshTime(state) {
                if (state.refreshTime) clearTimeout(state.refreshTime)
                state.refreshTime = null
            },

            /**
             * 设置全局主题
             * @param state
             * @param theme
             */
            setWindowTheme (state, theme) {
                state._systemConfig.theme = theme
                $("body").removeClass().addClass(theme)
            },

            /**
             * 设置菜单主题
             * @param state
             * @param theme
             */
            setMenuTheme (state, theme) {
                state._systemConfig.menuTheme = theme
            },

            /**
             * 设置全局配置
             * @param state
             * @param theme
             */
            setSystemConfig (state, config) {
                state._systemConfig = Object.assign(state._systemConfig, config)
                $("body").removeClass().addClass(state._systemConfig.theme)
                sessionStorage.setItem("_systemConfig", JSON.stringify(state._systemConfig))
            },

            /**
             * 设置菜单数据
             * @param state
             * @param menuData
             */
            setMenuData (state, menuData) {
                state.menuData = menuData
                sessionStorage.setItem("_menuData", JSON.stringify(state.menuData))
            },

            /**
             * 设置路由数据
             * @param state
             * @param routerData
             */
            setRouterData (state, routerData) {
                state.routerData = routerData
                sessionStorage.setItem("_routerData", JSON.stringify(state.routerData))
            },

            /**
             * 设置接口数据
             * @param state
             * @param apiData
             */
            setApiData (state, apiData) {
                state.apiData = apiData
                sessionStorage.setItem("_apiData", JSON.stringify(state.apiData))
            },

            /*************************标签页路由相关*******************************/
            /**
             * 系统打开时恢复之前页面
             * @param state
             */
            recoveryPage (state) {
                let pageList = []
                let localPageList = sessionStorage.getItem('pageTab')
                if (localPageList) {
                    localPageList = JSON.parse(localPageList)
                    if (localPageList.length > 0) {
                        localPageList.forEach(page => {
                            pageList.push(page)
                        })
                    }
                    state.pagesList = pageList
                }
            },

            /**
             * 打开路由时，将页面信息添加到标签页数组
             * @param state
             * @param meta
             */
            addPageItem (state, route) {
                let fullPath = route.fullPath
                state.currentPagePath = fullPath
                let exitItem = state.pagesList.find(item => {
                    return item.fullPath === fullPath
                })
                if (!exitItem) {
                    state.pagesList.push({
                        name: route.name || '新标签页面',
                        fullPath: fullPath,
                        pageId: route.meta.pageId,
                        routerId: route.meta.routerId,
                        icon: route.meta.icon,
                        query: route.meta.query,
                        fullVue: route.vue,
                        unRead: 0,
                    })
                } else {
                    state.pagesList.forEach(item => {
                        if (item.fullPath === fullPath) {
                            item.fullVue = route.vue || null
                        }
                    })
                }
                // 保存路由记录
                state.pagesHistoryList.push(fullPath)
                this.commit('savePageLocal')
            },

            /**
             * 调整页面顺序
             * @param state
             * @param data
             */
            sortPageList (state, data) {
                let oldPage = state.pagesList[data.oldIndex]
                state.pagesList.splice(data.oldIndex, 1)
                state.pagesList.splice(data.newIndex, 0, oldPage)
                this.commit('savePageLocal')
            },

            /**
             * 改变tab页面标题
             * @param state
             * @param param
             */
            changePageTitle (state, param) {
                for (let i = 0; i < state.pagesList.length; i++) {
                    if (state.pagesList[i].fullPath === param.fullPath) {
                        state.pagesList[i].name = param.name
                        break
                    }
                }
                this.commit('savePageLocal')
            },

            /**
             * 更新页面状态
             * @param state
             * @param fullPath
             * @param vue
             */
            setPageChange (state, param) {
                state.pagesList.forEach(item => {
                    if (item.fullPath === param.fullPath) {
                        state.currentPagePath = item.fullPath
                    }
                })
            },

            /**
             * 关闭页面
             * @param state
             * @param fullPath
             */
            hiddenPage (state, fullPath) {
                for (let i = 0; i < state.pagesList.length; i++) {
                    if (state.pagesList[i].fullPath === fullPath && state.pagesList[i].fullVue) {
                        break
                    }
                }
                this.commit('savePageLocal')
            },

            /**
             * 关闭并销毁页面实例
             * @param state
             * @param fullPath
             */
            destroyPage (state, fullPath) {
                for (let i = 0; i < state.pagesList.length; i++) {
                    if (state.pagesList[i].fullPath === fullPath) {
                        state.pagesList.splice(i, 1)
                        break
                    }
                }

                // 删除路由历史中的当前页面
                if (state.pagesHistoryList.length > 0) {
                    for (let i = state.pagesHistoryList.length - 1; i >= 0; i--) {
                        if (state.pagesHistoryList[i].indexOf(fullPath) > -1) {
                            state.pagesHistoryList.splice(i, 1)
                        }
                    }
                }
                this.commit('savePageLocal')
            },

            /**
             * 重新设置页面参数
             * @param state
             * @param param
             */
            resetQuery (state, param) {
                for (let i = 0; i < state.pagesList.length; i++) {
                    if (state.pagesList[i].fullPath === param.fullPath) {
                        state.pagesList[i].query = param.query
                        break
                    }
                }
                this.commit('savePageLocal')
            },

            /**
             * 保存页面历史到本地
             * @param state
             */
            savePageLocal (state) {
                let pageTab = []
                state.pagesList.forEach(item => {
                    pageTab.push({
                        name: item.name,
                        fullPath: item.fullPath,
                        query: item.query,
                        icon: item.icon,
                        pageId: item.pageId,
                        routerId: item.routerId,
                        unRead: item.unRead,
                    })
                })
                sessionStorage.setItem('pageTab', JSON.stringify(pageTab))
            },

            /**
             * 清空页面历史
             * @param state
             */
            clearPage (state) {
                state.pagesList = []
                state.pagesHistoryList = []
                sessionStorage.removeItem('pageTab')
            },

            /**
             * 设置默认路由
             * @param state
             * @param defaultRoutePath
             */
            setDefaultRoutePath (state, defaultRoutePath) {
                state.defaultRoutePath = defaultRoutePath
            }
        },
        getters: {
            getUserInfo: state => {
                let userInfo = null
                if (state.userInfo) {
                    userInfo = state.userInfo
                } else if (sessionStorage.getItem("userInfo")) {
                    userInfo = JSON.parse(sessionStorage.getItem("userInfo"))
                    state.userInfo = userInfo
                }
                if (userInfo && (userInfo.token || sessionStorage.token)) {
                    sessionStorage.token = sessionStorage.token || userInfo.token
                    return userInfo
                } else {
                    return null
                }
            },
            getSystemConfig: state => {
                return state._systemConfig
            },
            getMenuData: state => {
                return state.menuData
            },
            getPagesList: state => {
                return state.pagesList
            },
            getCurrentPagePath: state => {
                return state.currentPagePath
            },
            getDefaultRoutePath: state => {
                return state.defaultRoutePath
            },
            getVueByPath: state => fullPath  => {
                let page = state.pagesList.find(item => {
                    return item.fullPath === fullPath
                })
                return page && page.fullVue ? page.fullVue : null
            },
            getApiList: state => {
                return state.apiData || []
            },
            /**
             * 根据路径查询当前页
             * @param statr
             * @returns {function(*): null}
             */
            getPageByPath: state => fullPath => {
                let page = state.pagesList.find(item => {
                    return item.fullPath === fullPath
                })
                return page ? page : null
            },

            /**
             * 上一页记录
             * @param state
             * @param fullPath
             */
            getPreviousPage: state => fullPath => {
                let currentIndex = 0, previousPageFullPath = null
                if (state.pagesHistoryList.length > 0) {
                    // 当前位置
                    for (let i = state.pagesHistoryList.length - 1; i >= 0; i--) {
                        if (state.pagesHistoryList[i].indexOf(fullPath) > -1) {
                            currentIndex = i
                            break
                        }
                    }
                    // 上一页
                    for (let i = state.pagesHistoryList.length - 1; i >= 0; i--) {
                        if (i < currentIndex && state.pagesHistoryList[i] !== fullPath) {
                            previousPageFullPath = state.pagesHistoryList[i]
                            break
                        }
                    }
                }
                let previousPage = state.pagesList.find(item => {
                    return item.fullPath === previousPageFullPath
                })
                return previousPage
            },
        }
    }
    constructor() {
        this.store = createStore(this.options)
    }
    init() {
        return this.store
    }
}
